package com.tsd.core.jwt;

import com.tsd.core.config.Config;
import com.tsd.core.utils.HlpUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import javax.xml.bind.DatatypeConverter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName: JwtUtils
 * @Description: TODO
 * @Author: Hillpool
 * @Date: 2024/4/16 15:31
 * @Version: 1.0
 */
public class JwtUtils {

    private static String ENCODING_AES_KEY;
    private static final Integer TOKEN_EXPIRED_SECONDS;
    private static final Long TOKEN_EXPIRED_MS;

    static {
        ENCODING_AES_KEY = Config.getParameterValue("encodingAESKey");
        Integer integer;
        String tokenExpiredSeconds = Config.getParameterValue("tokenExpiredSeconds");
        if (!HlpUtils.isEmpty(tokenExpiredSeconds)) {
            try {
                integer = Integer.parseInt(tokenExpiredSeconds);
            } catch (Exception e) {
                integer = 7200;
            }
        } else {
            integer = 7200;
        }
        TOKEN_EXPIRED_SECONDS = integer;
        TOKEN_EXPIRED_MS = integer.longValue() * 1000;
    }

    public static Claims parseJWT(String jsonWebToken, String base64Security) {
        try {
            byte[] bytes = DatatypeConverter.parseBase64Binary(base64Security);
            return Jwts.parser().setSigningKey(bytes)
                    .parseClaimsJws(jsonWebToken).getBody();
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 从token中获取Map
     *
     * @param token
     * @return
     */
    public static Map<String, Object> getMapFromToken(String token) {
        if (HlpUtils.isEmpty(ENCODING_AES_KEY)) {
            ENCODING_AES_KEY = Config.getParameterValue("encodingAESKey");
        }
        Claims claims = parseJWT(token, ENCODING_AES_KEY);
        if (claims != null) {
            Map<String, Object> map = new HashMap<String, Object>(16);
            Set<String> keys = claims.keySet();
            for (String name : keys) {
                map.put(name, claims.get(name));
            }
            return map;
        } else {
            return null;
        }
    }

    public static String getEncodingAesKey() {
        return ENCODING_AES_KEY;
    }

    public static Integer getTokenExpiredSeconds() {
        return TOKEN_EXPIRED_SECONDS;
    }

    public static Long getTokenExpiredMs() {
        return TOKEN_EXPIRED_MS;
    }
}
